package com.bookstore.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bookstore.entity.Favorite;
import com.bookstore.mapper.FavoriteMapper;
import com.bookstore.service.FavoriteService;
import org.springframework.stereotype.Service;
import java.util.List;

@Service
public class FavoriteServiceImpl extends ServiceImpl<FavoriteMapper, Favorite> implements FavoriteService {

    @Override
    public boolean addFavorite(Favorite favorite) {
        // 检查是否已收藏
        if (isFavorite(favorite.getUserId(), favorite.getBookId())) {
            throw new IllegalArgumentException("已收藏该图书");
        }
        return save(favorite);
    }

    @Override
    public boolean removeFavorite(Integer favoriteId) {
        return removeById(favoriteId);
    }

    @Override
    public boolean updateRemark(Integer favoriteId, String remark) {
        Favorite favorite = getById(favoriteId);
        if (favorite == null) {
            throw new IllegalArgumentException("收藏记录不存在");
        }
        favorite.setRemark(remark);
        return updateById(favorite);
    }

    @Override
    public List<Favorite> getUserFavorites(Integer userId) {
        LambdaQueryWrapper<Favorite> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Favorite::getUserId, userId)
                .orderByDesc(Favorite::getCreatedAt);
        return list(queryWrapper);
    }

    @Override
    public boolean isFavorite(Integer userId, Integer bookId) {
        LambdaQueryWrapper<Favorite> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Favorite::getUserId, userId)
                .eq(Favorite::getBookId, bookId);
        return count(queryWrapper) > 0;
    }
} 